package com.dk.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dk.mapper.RoleMenuMapper;
import com.dk.mapper.TRoleMapper;
import com.dk.pojo.RoleMenuExample;
import com.dk.pojo.TPerson;
import com.dk.pojo.TRole;
import com.dk.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@org.springframework.stereotype.Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private TRoleMapper tRoleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<TRole> selectRole() {
        List<TRole> list = tRoleMapper.selectByExample(null);
        return list;
    }

    //角色增加
    @Override
    @Transactional
    public Boolean insertRole(TRole tRole, Integer[] id) {
        try {
            //增加角色 并返回id
            tRoleMapper.insertRole(tRole);
            Integer roleId = tRole.getRoleId();
            //增加中间表
            roleMenuMapper.insertRoleMenu(roleId,id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    //查询当前校色信息
    @Override
    public TRole selectByRid(Integer rid) {
        TRole tRole = tRoleMapper.selectByPrimaryKey(rid);
        return tRole;
    }

    //角色修改
    @Override
    @Transactional
    public Boolean updateRole(TRole tRole, Integer[] mids) {
        try {
            //修改角色
            tRoleMapper.updateByPrimaryKeySelective(tRole);
            //删除中间表
            RoleMenuExample rm = new RoleMenuExample();
            RoleMenuExample.Criteria criteria = rm.createCriteria();
            criteria.andRoleIdEqualTo(tRole.getRoleId());
            roleMenuMapper.deleteByExample(rm);
            //增加中间表
            roleMenuMapper.insertRoleMenu(tRole.getRoleId(),mids);
            //更新redis
            redisTemplate.delete("user_tree");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    //删除角色表
    @Override
    public Boolean deleteRole(Integer id) {
        try {
            //删除角色
            tRoleMapper.deleteByPrimaryKey(id);
            //删除中间表
            RoleMenuExample rm = new RoleMenuExample();
            RoleMenuExample.Criteria criteria = rm.createCriteria();
            criteria.andRoleIdEqualTo(id);
            roleMenuMapper.deleteByExample(rm);
            //更新redis
            redisTemplate.delete("user_tree");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

}
